package lion.framework.core.web.views;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;

import lion.dev.io.MimeTypeUtil;
import lion.framework.core.conf.Config;
import lion.framework.core.conf.ConfigManager;
import lion.framework.core.web.anno.ViewType;

/**
 * 视图查找model或HttpServletRequest中设置的"content" 内容，
 * 并以流的形式返回数据，数据可以是byte数组，也可以是InputStream, <br/>
 * 需要设置下载流的名称，通过name属性设置,使用500K的buffersize
 *
 * 请求传入参数：
 * 
 * @param name
 *            流文件名称
 * @param stream
 *            可以是byte[]，也可以是InputStream
 *
 *            <pre>
 * time   2013 2013-5-14 下午05:22:18
 * mail   hl_0074@sina.com
 *            </pre>
 *
 * @author lion
 */
@ViewType("stream")
public class StreamView implements IView {

	public static final String VIEW_TYPE = "stream";
	private String name;
	// private static final int BUFFER_SIZE = 1024 * 500;// 500KB

	@Override
	public void render(HttpServletRequest request, HttpServletResponse response) throws Exception {

		Object o = request.getAttribute("stream");

		if (o == null) { return; }
		if (!(o instanceof byte[] || o instanceof InputStream)) { return; }

		String fileName = (String) request.getAttribute("name");
		response.setContentType("application/octet-stream");
		if (StringUtils.isNotBlank(fileName)) {
			response.setContentType(MimeTypeUtil.getMimeType(fileName));
			Config config = ConfigManager.getConfig("framework");
			response.setHeader("Content-Disposition", "inline;filename=" + URLEncoder.encode(fileName, config.getString("framework.sysencoding", "UTF-8")));
		}

		if (o instanceof byte[]) {
			byte[] buf = (byte[]) o;
			response.setContentLength(buf.length);
			response.getOutputStream().write(buf);
		} else if (o instanceof InputStream) {

			InputStream is = (InputStream) o;
			response.setContentLength(is.available());
			OutputStream os = response.getOutputStream();
			response.setContentLength(is.available());

			IOUtils.copyLarge(is, response.getOutputStream());
			is.close();
			os.close();
		}
	}

	@Override
	public String getName() {

		return name;
	}

	@Override
	public String type() {

		return VIEW_TYPE;
	}

}
